package com.canbot.u05.activity.customvoice.tool

import android.content.Context
import android.os.AsyncTask
import android.os.Handler
import android.os.Looper

import com.canbot.u05.R
import com.canbot.u05.activity.customvoice.CustomDialogActivity
import com.canbot.u05.activity.customvoice.bean.AnswerBean
import com.canbot.u05.activity.customvoice.bean.CustomDialogExcelDatas
import com.canbot.u05.activity.customvoice.bean.QuestionBean
import com.canbot.u05.activity.loge

import com.canbot.u05.utils.ToastTools

import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.util.ArrayList
import java.util.regex.Pattern

import jxl.Sheet
import jxl.Workbook
import jxl.read.biff.BiffException
import java.lang.ref.WeakReference

/**
 * CustomDialogExcelLoader
 *
 * @author liu.heng
 * @date 2018/5/30
 */

class CustomDialogExcelLoader(private val context: WeakReference<Context>) : AsyncTask<String, Void, ArrayList<CustomDialogExcelDatas>>() {

    companion object {

        private const val TAG = "CustomDialogExcelLoader"

        private const val AUDIO_PREFIX = "/uusound/"

        private const val IMAGE_PREFIX = "/uupic/"

        private const val LIMIT_NUM = 10001

        private val SPACE_PATTERN = Pattern.compile("\\s*|\t|\r|\n")

        private val SYMBOLS_PATTERN = Pattern.compile("[`~!@#$%^&*()+=|{}':;,\\[\\].<>/?！￥… amp（）—【】‘；：”“’。，、？-]")

        /**
         * 移除字符串中的特殊字符
         */
        private fun replaceStr(str: String?): String {
            var question = ""
            if (str != null) {
//                val m = SPACE_PATTERN.matcher(str)
//                question = m.replaceAll("")
//                val q = SYMBOLS_PATTERN.matcher(question)
                question = str
            }
            return question
        }
    }

    override fun doInBackground(vararg params: String): ArrayList<CustomDialogExcelDatas> {
        return getXlsData(params[0])
    }

    override fun onPostExecute(officeList: ArrayList<CustomDialogExcelDatas>?) {

        if (officeList != null) {
            val a = context.get() as CustomDialogActivity
            a.update(officeList)
        }
    }

    /**
     * 获取 excel 表格中的数据,不能在主线程中调用
     */
    private fun getXlsData(xlsName: String): ArrayList<CustomDialogExcelDatas> {

        val file = File(xlsName)
        if (!file.exists()) {
            Thread(object : Runnable {
                private val handler = Handler(Looper.getMainLooper())

                override fun run() {
                    handler.post {
                        /**放在UI线程弹Toast*/
                        ToastTools.newInstance(context.get()).showText(context.get()?.getString(R.string.wrong_file_format))
                    }
                }
            }).start()
        }

        val beanList = ArrayList<CustomDialogExcelDatas>()

        try {
            val workbook = Workbook.getWorkbook(FileInputStream(file))
            val sheet = workbook.getSheet(0)

            val sheetNum = workbook.numberOfSheets
            val sheetRows = sheet.rows
            val sheetColumns = sheet.columns

            loge("$TAG the num of sheets is $sheetNum")
            loge("$TAG the name of sheet is  " + sheet.name)
            loge("$TAG total rows is 行=$sheetRows")
            loge("$TAG total cols is 列=$sheetColumns")

            if (sheetRows > LIMIT_NUM) {
                Thread(object : Runnable {
                    private val handler = Handler(Looper.getMainLooper())

                    override fun run() {
                        handler.post {
                            /**放在UI线程弹Toast*/
                            ToastTools.newInstance(context.get()).showText(context.get()?.getString(R.string.more_rows_table_data))
                        }
                    }
                }).start()
            }

            if (sheetColumns == 3) {
                /**自定义对话 2.0 (问题;回答(TTS或音频名字);图片名字)*/
                getDuoWenDuoDaData(sheetRows, sheet, beanList)
                loge("$TAG ${beanList[0].listQsBean}")
                loge("$TAG ${beanList[0].listAsBean}")
                loge("$TAG ${beanList.size}")
            } else {
                /**自定义对话 2.0 (问题;回答(TTS或音频名字))*/
                getDuoWenDuoDaDataNoImage(sheetRows, sheet, beanList)
            }


            workbook.close()

        } catch (e: IOException) {
            loge("$TAG $e")
        } catch (e: BiffException) {
            loge("$TAG $e")
        }

        return beanList
    }

    /**
     * 获取多问多答的数据
     *
     * @param sheetRows excel的行数
     * @param sheet     excel的sheet
     */
    private fun getDuoWenDuoDaData(sheetRows: Int, sheet: Sheet, beanList: ArrayList<CustomDialogExcelDatas>) {

        val answers = ArrayList<AnswerBean>()
        val questions = ArrayList<QuestionBean>()

        for (i in 1 until sheetRows) {
            val question = replaceStr(sheet.getCell(0, i).contents)
            val answer = sheet.getCell(1, i).contents
            val imagePath = sheet.getCell(2, i).contents

            if (question.isEmpty() && answer.isEmpty() && imagePath.isEmpty()) {

                val questionBeans = ArrayList(questions)
                val answerBeans = ArrayList(answers)

                val judgeEntity = CustomDialogExcelDatas()
                judgeEntity.listAsBean = answerBeans
                judgeEntity.listQsBean = questionBeans
                beanList.add(judgeEntity)
                loge("$TAG $answers")
                loge("$TAG $questions")
                loge("$TAG ${judgeEntity.listQsBean}")
                answers.clear()
                questions.clear()
            } else {
                if (question.isNotEmpty()) {
                    val questionBean = QuestionBean()
                    questionBean.question = question
                    questionBean.type = 1
                    questions.add(questionBean)
                }

                if (answer.isNotEmpty()) {
                    val answerBean = AnswerBean()
                    /**判断图片行是否有内容*/
                    if (imagePath.isNotEmpty()) {
                        answerBean.imgpath = IMAGE_PREFIX + imagePath
                    }
                    /**判断回答内容是TTS还是音频*/
                    if (answer.endsWith(".mp3") || answer.endsWith(".wav")) {
                        answerBean.soundpath = AUDIO_PREFIX + answer
                        answerBean.type = 0
                    } else {
                        answerBean.ttstext = answer
                        answerBean.type = 1
                    }
                    answers.add(answerBean)
                }

                if (i == sheetRows - 1) {
                    val judgeEntity = CustomDialogExcelDatas()
                    judgeEntity.listAsBean = answers
                    judgeEntity.listQsBean = questions
                    beanList.add(judgeEntity)
                    loge("$TAG $answers")
                    loge("$TAG $questions")
                    loge("$TAG ${judgeEntity.listAsBean}")
                }
            }
        }
    }

    /**
     * 获取多问多答的数据
     *
     * @param sheetRows excel的行数
     * @param sheet     excel的sheet
     */
    private fun getDuoWenDuoDaDataNoImage(sheetRows: Int, sheet: Sheet, beanList: ArrayList<CustomDialogExcelDatas>) {

        val answers = ArrayList<AnswerBean>()
        val questions = ArrayList<QuestionBean>()

        for (i in 1 until sheetRows) {
            val question = replaceStr(sheet.getCell(0, i).contents)
            val answer = sheet.getCell(1, i).contents

            if (question.isEmpty() && answer.isEmpty()) {

                val questionBeans = ArrayList(questions)
                val answerBeans = ArrayList(answers)

                val judgeEntity = CustomDialogExcelDatas()
                judgeEntity.listAsBean = answerBeans
                judgeEntity.listQsBean = questionBeans
                beanList.add(judgeEntity)
                answers.clear()
                questions.clear()
            } else {

                if (question.isNotEmpty()) {
                    val questionBean = QuestionBean()
                    questionBean.question = question
                    questionBean.type = 1
                    questions.add(questionBean)
                }

                if (answer.isNotEmpty()) {
                    val answerBean = AnswerBean()
                    /**判断回答内容是TTS还是音频*/
                    if (answer.endsWith(".mp3") || answer.endsWith(".wav")) {
                        answerBean.soundpath = AUDIO_PREFIX + answer
                        answerBean.type = 0
                    } else {
                        answerBean.ttstext = answer
                        answerBean.type = 1
                    }
                    answers.add(answerBean)
                }
                if (i == sheetRows - 1) {
                    val judgeEntity = CustomDialogExcelDatas()
                    judgeEntity.listAsBean = answers
                    judgeEntity.listQsBean = questions
                    beanList.add(judgeEntity)
                }
            }
        }
    }

}
